import NextAuth, { Session, DefaultSession } from "next-auth";
import { getUserById } from "@/data/user";
import authConfig from "@/auth.config";
import { UserRole } from "./types/user.d";
import { JWT } from "next-auth/jwt";
import * as dotenv from "dotenv";
dotenv.config();
export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  trustHost: true,
  pages: {
    signIn: "/auth/login",
    error: "/auth/error",
  },
  // events: {
  //   async signOut(message: {
  //     session?: AdapterSession | null;
  //     token?: JWT | null;
  //   }) {
  //     if ("token" in message) {
  //       message.token = null;
  //     }
  //     if ("session" in message) {
  //       message.session = null;
  //     }
  //   },
  // },

  callbacks: {
    async signIn({ user, account }) {
      // Allow OAuth without email verification
      if (account?.provider !== "credentials") return true;
      return true;
    },

    async session({
      token,
      session,
    }: {
      token: JWT;
      session: Session;
    }): Promise<Session | DefaultSession> {
      if (!token) {
        return {
          user: {
            // Default user properties
          },
          // other default session properties
        } as DefaultSession;
      }

      if (token.sub && session.user) {
        session.user.name = token.name || "";
        session.user.email = token.email || "";

        session.user.id = token.sub;
      }

      if (token.role && session.user) {
        session.user.role = token.role as UserRole;
      }
      return session;
    },
    async jwt({ token }) {
      if (!token.sub) return token;
      const existingUser = await getUserById(token.sub);
      //console.log(`jwt ${token.sub} existing user ${existingUser.name}`);

      if (!existingUser) return token;

      //const existingAccount = await getAccountByUserId(existingUser.id);

      token.isOAuth = !!existingUser;
      token.name = existingUser.name;
      token.email = existingUser.email;
      token.role = existingUser.role;
      token.isTwoFactorEnabled = existingUser.isTwoFactorEnabled;
      return token;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
  debug: true,
  session: { strategy: "jwt" },
  ...authConfig,
});
